package net.lb.socketserver.transfer.server;

import net.lb.beancontext.core.BeanContext;
import net.lb.beancontext.core.BeanContextImpl;
import net.lb.beancontext.core.bean.BeanConfig;
import net.lb.socketserver.util.HeadFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ServerMain
{
    protected AioServer   aioServer;
    protected BeanContext beanContext;
    private Logger        logger = LogManager.getLogger();
    
    protected ServerMain()
    {
        
    }
    
    public ServerMain(ServerConfig serverConfig, BeanConfig... beanConfigs)
    {
        serverConfig.addPackageNames("net.lb.socketserver:out~net.lb.socketserver*auth");
        init(serverConfig, beanConfigs);
    };
    
    protected void init(ServerConfig serverConfig, BeanConfig... beanConfigs)
    {
        beanContext = new BeanContextImpl(serverConfig.getPackageNames());
        for (BeanConfig each : beanConfigs)
        {
            beanContext.addBeanConfig(each);
        }
        beanContext.addSingletonEntity(ServerConfig.class.getName(), serverConfig);
        beanContext.addSingletonEntity(HeadFactory.class.getName(), serverConfig.getHeadFactory());
        beanContext.initContext();
        aioServer = (AioServer) beanContext.getBean(AioServer.class.getName());
    }
    
    /**
     * 使用初始化的时候的端口启动服务器
     */
    public void start()
    {
        aioServer.start();
    }
    
    public void stop()
    {
        logger.warn("服务器被指令关闭");
        aioServer.stop();
    }
    
    /**
     * 返回服务器内部使用的beancontext实例
     * 
     * @return
     */
    public BeanContext getContext()
    {
        return beanContext;
    }
}
